﻿using Pay.Window.Data.Dto;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Pay.Window.Data.Utilitys
{
    public class WebHelper
    {
        /// <summary>
        /// 获取最新订单信息
        /// </summary>
        /// <param name="systemAccount"></param>
        /// <param name="web"></param>
        /// <returns></returns>
        public static IList<WindowOrderInput> GetAlipayNewOrders(string systemAccount, WebBrowser web)
        {
            HtmlDocument doc = web.Document;
            HtmlElementCollection tbs = doc.GetElementsByTagName("table");

            var datas = DataHelper.GetData(systemAccount);

            foreach (HtmlElement tb in tbs)
            {
                if (tb.GetAttribute("id") == "tradeRecordsIndex")
                {
                    HtmlElementCollection trs = tb.GetElementsByTagName("tr");
                    if (trs.Count > 0)
                    {
                        foreach (HtmlElement tr in trs)
                        {
                            HtmlElementCollection tds = tr.GetElementsByTagName("td");
                            if (tds.Count > 0)
                            {
                                // 0.创建时间
                                // 1.null
                                // 2.名称 - 在扫收款码后,该商品名称为收款码预留备注信息
                                // 3.商户订单号 | 交易号
                                // 4.对方
                                // 5.金额
                                // 6.明细
                                // 7.状态
                                // 8.操作

                                var creationTime = AlipayDateFormat(tds[0].InnerText);
                                var des = AlipayDesFormat(tds[2].InnerText);
                                var orderNo = AlipayNoFormat(tds[3].InnerText);
                                var amount = AlipayAmountFormat(tds[5].InnerText);
                                var status = AlipayStatusFormat(tds[7].InnerText);

                                if (datas.FirstOrDefault(s => s.OrderNo == orderNo) == null && amount > 0)
                                {
                                    var data = new WindowOrderInput
                                    {
                                        Des = des,
                                        CreateTime = creationTime,
                                        Amount = amount,
                                        OrderNo = orderNo,
                                        Status = status,
                                        SystemAccount = systemAccount,
                                        IsSubmit = false
                                    };
                                    DataHelper.AddData(systemAccount, data);
                                }
                            }
                        }
                    }
                }
            }

            var orders = DataHelper.GetData(systemAccount);

            // 按照时间正序排列
            var newOrders = orders.Where(s => s.IsSubmit == false).OrderBy(s => s.CreateTime).ToList();

            if (newOrders.Count > 0)
            {
                DataHelper.Save(systemAccount);
            }
            return newOrders;
        }

        private static string AlipayDesFormat(string input)
        {
            var s = input?.Trim();
            return s;
        }

        private static DateTime AlipayDateFormat(string input)
        {
            var s = Regex.Replace(input, "[^0-9 .:]", "");// dateReg.Replace(date, "");
            DateTime d;
            DateTime.TryParse(s, out d);
            return d;
        }

        private static decimal AlipayAmountFormat(string input)
        {
            var s = Regex.Replace(input, "[^-+0-9.]", "");
            decimal amount;
            decimal.TryParse(s, out amount);
            return amount;
        }

        private static string AlipayNoFormat(string input)
        {
            // 支付宝订单号是由两种单号组合的一个单元格,此时我们需要的是交易号或流水号,需要切割开
            var nos = input.Split('|');
            var no = string.Empty;
            if (nos.Length == 1)
            {
                no = Regex.Replace(nos[0], "[^0-9]", "");
            }
            else if (nos.Length == 2)
            {
                no = Regex.Replace(nos[1], "[^0-9]", "");
            }
            else
            {
                // 不处理这种情况
            }
            return no;
        }

        private static WindowOrderStatus AlipayStatusFormat(string input)
        {
            if (input.Contains("关闭"))
            {
                return WindowOrderStatus.Closed;
            }
            else if (input.Contains("失败"))
            {
                return WindowOrderStatus.Failed;
            }
            else if (input.Contains("未支付"))
            {
                return WindowOrderStatus.UnPaid;
            }
            else if (input.Contains("成功"))
            {
                return WindowOrderStatus.Paid;
            }
            else
            {
                return WindowOrderStatus.Default;
            }
        }
    }
}
